package com.muye.dianli.activity;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.entity.mime.content.StringBody;

import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnKeyListener;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.util.SparseArray;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.onekeyshare.OnekeyShare;

import com.google.gson.Gson;
import com.muye.adapter.CommodityDetailInfoAdapter;
import com.muye.adapter.OrderDetailViewPagerAdapter;
import com.muye.constant.C;
import com.muye.constant.ConstantPersonalInfo;
import com.muye.constant.U;
import com.muye.dianli.R;
import com.muye.dianli.fragment.CommodityDetailViewPagerPictureFragment;
import com.muye.field.FollowDetailData;
import com.muye.field.FollowDetailField;
import com.muye.field.ShoppingCartField;
import com.tangchao.view.NoScrollListView;
import com.zvezda.algorithm.utils.MD5;
import com.zvezda.http.utils.HttpConst;
import com.zvezda.http.utils.KeyValue;
import com.zvezda.http.utils.RequestHttpListener;
import com.zvezda.http.utils.RequestHttpPostThread;

/**
 * 商品详情(收藏详情)
 * 
 * @author TangChao
 *
 */
public class FollowDetailActivity extends FragmentActivity implements OnClickListener, OnKeyListener, TextWatcher
{
	/**
	 * 订单ID
	 */
	private String followId;
	
	/**
	 * 订单Type
	 */
	private String followType;
	
	/**
	 * ViewPager
	 */
	private ViewPager viewPager;
	
	/**
	 * ViewPager适配器
	 */
	private OrderDetailViewPagerAdapter adapter;
	
	/**
	 * 请求数据的线程
	 */
	private RequestHttpPostThread requestHttpPostThread;
	
	/**
	 * 数据源
	 */
	private FollowDetailData followDetailData;
	
	/**
	 * 详情按钮
	 */
	private TextView detailsBtn;
	
	/**
	 * 规格按钮
	 */
	private TextView standardBtn;
	
	/**
	 * 评论按钮
	 */
	private TextView commentBtn;
	
	/**
	 * 分享、发送按钮
	 */
	private TextView share_sendBtn;
	
	/**
	 * 订购按钮
	 */
	private TextView purchaseBtn;
	
	/**
	 * 评论内容输入框
	 */
	private EditText inputCommentContent;
	
	/**
	 * 评论内容
	 */
	private String commentContent;
	
	/**
	 * 图片缓存路径
	 */
	private String filePath;
	
	/**
	 * 信息列表
	 */
	private NoScrollListView infoListView;
	
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		getWindow().setFormat(PixelFormat.RGBA_8888);
		setContentView(R.layout.commodity_detail_layout);
		filePath = C.FILE_PATH + "/DianLi";
		File file = new File(filePath);
		if (!file.exists())
		{
			file.mkdirs();
		}
		try
		{
			followId = getIntent().getStringExtra("FOLLOW_ID");
			Log.i(C.TAG, "订单id为----->" + followId);
			followType = getIntent().getStringExtra("FOLLOW_TYPE");
			Log.i(C.TAG, "订单type为----->" + followType);
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		followId = "76";
		followType = "0";
		createTitle();
		initWidget();
		getFollowDetail();
		ShareSDK.initSDK(this);
	}
	
	@Override
	protected void onDestroy()
	{
		ShareSDK.stopSDK(this);
		super.onDestroy();
	}
	
	/**
	 * 初始化标题栏
	 */
	private void createTitle()
	{
		TextView titleName = (TextView) findViewById(R.id.title_bar_name_text_view);
		titleName.setText("商品详情");
		titleName.setTextColor(getResources().getColor(R.color.white));
		ImageView leftBtn = (ImageView) findViewById(R.id.title_bar_left_image_view);
		leftBtn.setImageResource(R.drawable.title_back_icon);
		leftBtn.setVisibility(View.VISIBLE);
		leftBtn.setOnClickListener(this);
		ImageView rightBtn = (ImageView) findViewById(R.id.title_bar_right_image_view);
		rightBtn.setImageResource(R.drawable.shopping_cart_icon);
		rightBtn.setVisibility(View.VISIBLE);
		rightBtn.setOnClickListener(this);
	}
	
	/**
	 * 初始化控件
	 */
	private void initWidget()
	{
		// 详情
		detailsBtn = (TextView) findViewById(R.id.commodity_detail_layout_info_details);
		detailsBtn.setBackgroundColor(getResources().getColor(R.color.transparent_white));
		detailsBtn.setOnClickListener(this);
		// 规格
		standardBtn = (TextView) findViewById(R.id.commodity_detail_layout_info_standard);
		standardBtn.setOnClickListener(this);
		// 评论
		commentBtn = (TextView) findViewById(R.id.commodity_detail_layout_info_comment);
		commentBtn.setOnClickListener(this);
		/* =========================================== */
		// 收藏按钮
		ImageView followBtn = (ImageView) findViewById(R.id.commodity_detail_layout_share);
		followBtn.setOnClickListener(this);
		share_sendBtn = (TextView) findViewById(R.id.commodity_detail_layout_share_send);
		share_sendBtn.setText("分享");
		share_sendBtn.setOnClickListener(this);
		purchaseBtn = (TextView) findViewById(R.id.commodity_detail_layout_purchase);
		purchaseBtn.setVisibility(View.VISIBLE);
		purchaseBtn.setOnClickListener(this);
		inputCommentContent = (EditText) findViewById(R.id.commodity_detail_layout_comment_content_edit);
		inputCommentContent.setVisibility(View.GONE);
		inputCommentContent.addTextChangedListener(this);
		// 加入购物车
		TextView addToCartBtn = (TextView) findViewById(R.id.commodity_detail_layout_add_shopping_cart);
		addToCartBtn.setOnClickListener(this);
		/* =========================================== */
		viewPager = (ViewPager) findViewById(R.id.commodity_detail_layout_view_pager);
		// List<HashMap<String, Object>> arrayList = new ArrayList<HashMap<String, Object>>();
		// for (int i = 0; i < 5; i++)
		// {
		// OrderDetailViewPagerPictureFragment fragment = new OrderDetailViewPagerPictureFragment();
		// HashMap<String, Object> hashMap = new HashMap<String, Object>();
		// hashMap.put("VIEW", fragment);
		// hashMap.put("PICTURE", i + "");
		// arrayList.add(hashMap);
		// }
		// adapter = new OrderDetailViewPagerAdapter(getSupportFragmentManager(), arrayList);
		// viewPager.setAdapter(adapter);
	}
	
	/**
	 * 请求商品详情
	 */
	private void getFollowDetail()
	{
		C.openPragressDialog(this, this, R.string.in_request_data);
		ArrayList<KeyValue<String, Object>> paramsList = new ArrayList<KeyValue<String, Object>>();
		String str = C.APPID + followId + followType + C.CONSTANT;
		try
		{
			paramsList.add(new KeyValue<String, Object>("appId", new StringBody(C.APPID, Charset.forName("utf-8"))));
			paramsList.add(new KeyValue<String, Object>("id", new StringBody(followId, Charset.forName("utf-8"))));
			paramsList.add(new KeyValue<String, Object>("type", new StringBody(followType, Charset.forName("utf-8"))));
			paramsList.add(new KeyValue<String, Object>("sign", new StringBody(MD5.getMD5_32(str), Charset.forName("utf-8"))));
		}
		catch (UnsupportedEncodingException e)
		{
			e.printStackTrace();
		}
		requestHttpPostThread = new RequestHttpPostThread(getFollowDetailListener, U.GET_DETAIL, paramsList);
		requestHttpPostThread.start();
	}
	
	/**
	 * 请求商品详情返回监听
	 */
	private RequestHttpListener getFollowDetailListener = new RequestHttpListener()
	{
		
		@Override
		public void requestHttp(Message msg)
		{
			Bundle bundle = msg.getData();
			int result = bundle.getInt(HttpConst.ACTION_RESULT, HttpConst.ACTION_FAIL);
			if (result == HttpConst.ACTION_SUCCESS)
			{
				byte[] dataArr = bundle.getByteArray(HttpConst.DATA_ARR);
				try
				{
					String str = new String(dataArr, "utf-8");
					Log.i(C.TAG, "请求收藏详情结果----->" + str);
					Gson gson = new Gson();
					FollowDetailField item = gson.fromJson(str, FollowDetailField.class);
					followDetailData = item.data;
				}
				catch (UnsupportedEncodingException e)
				{
					e.printStackTrace();
				}
				Message message = new Message();
				message.what = 0;
				message.arg1 = result;
				handler.sendMessage(message);
			}
		}
	};
	
	/**
	 * 请求创建评论
	 */
	private void createComment(String content)
	{
		C.openPragressDialog(this, this, R.string.in_request_data);
		ArrayList<KeyValue<String, Object>> paramsList = new ArrayList<KeyValue<String, Object>>();
		String str = C.APPID + content + followId + followType + ConstantPersonalInfo.uid + C.CONSTANT;
		try
		{
			paramsList.add(new KeyValue<String, Object>("appId", new StringBody(C.APPID, Charset.forName("utf-8"))));
			paramsList.add(new KeyValue<String, Object>("id", new StringBody(followId, Charset.forName("utf-8"))));
			paramsList.add(new KeyValue<String, Object>("type", new StringBody(followType, Charset.forName("utf-8"))));
			paramsList.add(new KeyValue<String, Object>("discuss", new StringBody(content, Charset.forName("utf-8"))));
			paramsList
					.add(new KeyValue<String, Object>("uid", new StringBody(ConstantPersonalInfo.uid, Charset.forName("utf-8"))));
			paramsList.add(new KeyValue<String, Object>("sign", new StringBody(MD5.getMD5_32(str), Charset.forName("utf-8"))));
		}
		catch (UnsupportedEncodingException e)
		{
			e.printStackTrace();
		}
		requestHttpPostThread = new RequestHttpPostThread(createCommentListener, U.CREATE_COMMENT, paramsList);
		requestHttpPostThread.start();
	}
	
	/**
	 * 请求创建评论返回监听
	 */
	private RequestHttpListener createCommentListener = new RequestHttpListener()
	{
		
		@Override
		public void requestHttp(Message msg)
		{
			Bundle bundle = msg.getData();
			int result = bundle.getInt(HttpConst.ACTION_RESULT, HttpConst.ACTION_FAIL);
			if (result == HttpConst.ACTION_SUCCESS)
			{
				byte[] dataArr = bundle.getByteArray(HttpConst.DATA_ARR);
				try
				{
					String str = new String(dataArr, "utf-8");
					Log.i(C.TAG, "请求创建评论结果----->" + str);
				}
				catch (UnsupportedEncodingException e)
				{
					e.printStackTrace();
				}
				Message message = new Message();
				message.what = 1;
				message.arg1 = result;
				handler.sendMessage(message);
			}
		}
	};
	
	/**
	 * 请求创建评论
	 */
	private void follow()
	{
		C.openPragressDialog(this, this, R.string.in_request_data);
		ArrayList<KeyValue<String, Object>> paramsList = new ArrayList<KeyValue<String, Object>>();
		String str = C.APPID + "0" + followId + followType + ConstantPersonalInfo.uid + C.CONSTANT;
		try
		{
			paramsList.add(new KeyValue<String, Object>("appId", new StringBody(C.APPID, Charset.forName("utf-8"))));
			paramsList.add(new KeyValue<String, Object>("id", new StringBody(followId, Charset.forName("utf-8"))));
			paramsList.add(new KeyValue<String, Object>("type", new StringBody(followType, Charset.forName("utf-8"))));
			paramsList.add(new KeyValue<String, Object>("cancle", new StringBody("0", Charset.forName("utf-8"))));
			paramsList
					.add(new KeyValue<String, Object>("uid", new StringBody(ConstantPersonalInfo.uid, Charset.forName("utf-8"))));
			paramsList.add(new KeyValue<String, Object>("sign", new StringBody(MD5.getMD5_32(str), Charset.forName("utf-8"))));
		}
		catch (UnsupportedEncodingException e)
		{
			e.printStackTrace();
		}
		requestHttpPostThread = new RequestHttpPostThread(followListener, U.FOLLOW, paramsList);
		requestHttpPostThread.start();
	}
	
	/**
	 * 请求收藏返回监听
	 */
	private RequestHttpListener followListener = new RequestHttpListener()
	{
		
		@Override
		public void requestHttp(Message msg)
		{
			Bundle bundle = msg.getData();
			int result = bundle.getInt(HttpConst.ACTION_RESULT, HttpConst.ACTION_FAIL);
			if (result == HttpConst.ACTION_SUCCESS)
			{
				byte[] dataArr = bundle.getByteArray(HttpConst.DATA_ARR);
				try
				{
					String str = new String(dataArr, "utf-8");
					Log.i(C.TAG, "请求收藏结果----->" + str);
				}
				catch (UnsupportedEncodingException e)
				{
					e.printStackTrace();
				}
				Message message = new Message();
				message.what = 2;
				message.arg1 = result;
				handler.sendMessage(message);
			}
		}
	};
	
	/**
	 * 处理数据
	 */
	private Handler handler = new Handler()
	{
		
		@Override
		public void handleMessage(Message msg)
		{
			super.handleMessage(msg);
			C.closePragressDialog();
			switch (msg.what)
			{
				case 0:// 商品详情
					switch (msg.arg1)
					{
						case HttpConst.ACTION_SUCCESS:
							List<String> followDetailAlbums = followDetailData.albums;
							List<CommodityDetailViewPagerPictureFragment> arrayList = new ArrayList<CommodityDetailViewPagerPictureFragment>();
							try
							{
								for (int i = 0; i < followDetailAlbums.size(); i++)
								{
									CommodityDetailViewPagerPictureFragment fragment = new CommodityDetailViewPagerPictureFragment();
									fragment.setUrl(followDetailAlbums.get(i));
									arrayList.add(fragment);
								}
							}
							catch (Exception e)
							{
								e.printStackTrace();
							}
							adapter = new OrderDetailViewPagerAdapter(getSupportFragmentManager(), arrayList);
							viewPager.setAdapter(adapter);
							// 现价
							TextView priceText = (TextView) findViewById(R.id.commodity_detail_layout_price);
							priceText.setText("现价: " + followDetailData.price);
							infoListView = (NoScrollListView) findViewById(R.id.commodity_detail_layout_detail_list_view);
							CommodityDetailInfoAdapter infoAdapter = new CommodityDetailInfoAdapter(followDetailData.detail,
									FollowDetailActivity.this, filePath);
							infoListView.setAdapter(infoAdapter);
							break;
						case HttpConst.ACTION_FAIL:
							C.showToast(FollowDetailActivity.this, "请求失败,请重试");
							break;
						
						default:
							break;
					}
					break;
				case 1:// 创建评论
					switch (msg.arg1)
					{
						case HttpConst.ACTION_SUCCESS:
							C.showToast(FollowDetailActivity.this, "发送成功");
							inputCommentContent.setText("");
							break;
						case HttpConst.ACTION_FAIL:
							C.showToast(FollowDetailActivity.this, "发送失败,请重试");
							break;
						
						default:
							break;
					}
					break;
				case 2:// 收藏
					switch (msg.arg1)
					{
						case HttpConst.ACTION_SUCCESS:
							C.showToast(FollowDetailActivity.this, "收藏成功");
							break;
						case HttpConst.ACTION_FAIL:
							C.showToast(FollowDetailActivity.this, "收藏失败,请重试");
							break;
						
						default:
							break;
					}
					break;
				
				default:
					break;
			}
		}
		
	};
	
	/**
	 * 开启分享窗口
	 * 
	 * @param platform
	 * @param silent
	 */
	public void showOnekeyshare(String platform, boolean silent)
	{
		OnekeyShare oks = new OnekeyShare();
		
		// 分享时Notification的图标和文字
		oks.setNotification(R.drawable.ic_launcher, getApplicationContext().getString(R.string.app_name));
		// address是接收人地址，仅在信息和邮件使用
		oks.setAddress("12345678901");
		// title标题，印象笔记、邮箱、信息、微信、人人网和QQ空间使用
		oks.setTitle(getApplicationContext().getString(R.string.share));
		// titleUrl是标题的网络链接，仅在人人网和QQ空间使用
		oks.setTitleUrl("http://sharesdk.cn");
		// text是分享文本，所有平台都需要这个字段
		oks.setText(getApplicationContext().getString(R.string.share_content));
		// imagePath是图片的本地路径，Linked-In以外的平台都支持此参数
		// oks.setImagePath(MainActivity.TEST_IMAGE);
		// imageUrl是图片的网络路径，新浪微博、人人网、QQ空间、
		// 微信的两个平台、Linked-In支持此字段
		oks.setImageUrl("http://img.appgo.cn/imgs/sharesdk/content/2013/07/25/1374723172663.jpg");
		// url仅在微信（包括好友和朋友圈）中使用
		oks.setUrl("http://sharesdk.cn");
		// appPath是待分享应用程序的本地路劲，仅在微信中使用
		// oks.setAppPath(MainActivity.TEST_IMAGE);
		// comment是我对这条分享的评论，仅在人人网和QQ空间使用
		oks.setComment(getApplicationContext().getString(R.string.share));
		// site是分享此内容的网站名称，仅在QQ空间使用
		oks.setSite(this.getString(R.string.app_name));
		// siteUrl是分享此内容的网站地址，仅在QQ空间使用
		oks.setSiteUrl("http://sharesdk.cn");
		// venueName是分享社区名称，仅在Foursquare使用
		oks.setVenueName("Southeast in China");
		// venueDescription是分享社区描述，仅在Foursquare使用
		oks.setVenueDescription("This is a beautiful place!");
		// latitude是维度数据，仅在新浪微博、腾讯微博和Foursquare使用
		oks.setLatitude(23.122619f);
		// longitude是经度数据，仅在新浪微博、腾讯微博和Foursquare使用
		oks.setLongitude(113.372338f);
		// 是否直接分享（true则直接分享）
		oks.setSilent(silent);
		// 指定分享平台，和slient一起使用可以直接分享到指定的平台
		if (platform != null)
		{
			oks.setPlatform(platform);
		}
		// 去除注释可通过OneKeyShareCallback来捕获快捷分享的处理结果
		// oks.setCallback(new OneKeyShareCallback());
		// 通过OneKeyShareCallback来修改不同平台分享的内容
		oks.setShareContentCustomizeCallback(new ShareContentCustomizeDemo());
		
		oks.show(this);
	}
	
	@Override
	public void onClick(View v)
	{
		switch (v.getId())
		{
			case R.id.title_bar_left_image_view:
				finish();
				break;
			case R.id.title_bar_right_image_view:// 进入购物车按钮
				Intent intent = new Intent(FollowDetailActivity.this, ShoppingCartActivity.class);
				startActivity(intent);
				break;
			case R.id.commodity_detail_layout_info_details:// 详情按钮
				detailsBtn.setBackgroundColor(getResources().getColor(R.color.transparent_white));
				standardBtn.setBackgroundColor(getResources().getColor(R.color.transparent_black));
				commentBtn.setBackgroundColor(getResources().getColor(R.color.transparent_black));
				purchaseBtn.setVisibility(View.VISIBLE);
				inputCommentContent.setVisibility(View.GONE);
				share_sendBtn.setText("分享");
				infoListView.setVisibility(View.VISIBLE);
				break;
			case R.id.commodity_detail_layout_info_standard:// 规格按钮
				detailsBtn.setBackgroundColor(getResources().getColor(R.color.transparent_black));
				standardBtn.setBackgroundColor(getResources().getColor(R.color.transparent_white));
				commentBtn.setBackgroundColor(getResources().getColor(R.color.transparent_black));
				purchaseBtn.setVisibility(View.VISIBLE);
				inputCommentContent.setVisibility(View.GONE);
				share_sendBtn.setText("分享");
				infoListView.setVisibility(View.GONE);
				break;
			case R.id.commodity_detail_layout_info_comment:// 评论按钮
				detailsBtn.setBackgroundColor(getResources().getColor(R.color.transparent_black));
				standardBtn.setBackgroundColor(getResources().getColor(R.color.transparent_black));
				commentBtn.setBackgroundColor(getResources().getColor(R.color.transparent_white));
				purchaseBtn.setVisibility(View.GONE);
				inputCommentContent.setVisibility(View.VISIBLE);
				share_sendBtn.setText("发送");
				infoListView.setVisibility(View.GONE);
				break;
			case R.id.commodity_detail_layout_share:// 收藏按钮
				follow();
				break;
			case R.id.commodity_detail_layout_share_send:// 分享、发送按钮
				if (share_sendBtn.getText().equals("分享"))
				{
					showOnekeyshare("分享", false);
				}
				else if (share_sendBtn.getText().equals("发送"))
				{
					if (commentContent == null || commentContent.equals(""))
					{
						Toast.makeText(this, "请输入评论内容", Toast.LENGTH_SHORT).show();
						return;
					}
					createComment(commentContent);
				}
				break;
			case R.id.commodity_detail_layout_purchase:// 购买按钮
				
				break;
			case R.id.commodity_detail_layout_add_shopping_cart:// 加入购物车按钮
				SparseArray<ShoppingCartField> sparseArray = new SparseArray<ShoppingCartField>();
				ShoppingCartField item = new ShoppingCartField();
				item.image = followDetailData.logoUrl;
				item.title = followDetailData.title;
				item.content = followDetailData.summary;
				item.price = followDetailData.price;
				int i = 0;
				if (C.SHOPPING_CART_DATA == null)
				{
					C.SHOPPING_CART_DATA = new ArrayList<SparseArray<ShoppingCartField>>();
					i = 0;
				}
				else
				{
					i = C.SHOPPING_CART_DATA.size();
				}
				sparseArray.append(i, item);
				C.SHOPPING_CART_DATA.add(sparseArray);
				C.showToast(FollowDetailActivity.this, "添加成功");
				break;
			default:
				break;
		}
	}
	
	@Override
	public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event)
	{
		if (requestHttpPostThread != null)
		{
			requestHttpPostThread.interrupt();
			requestHttpPostThread.setRequestHttpListener(null);
		}
		return false;
	}
	
	@Override
	public void afterTextChanged(Editable s)
	{
		commentContent = inputCommentContent.getText().toString();
	}
	
	@Override
	public void beforeTextChanged(CharSequence s, int start, int count, int after)
	{
		
	}
	
	@Override
	public void onTextChanged(CharSequence s, int start, int before, int count)
	{
		
	}
	
	/**
	 * 点击空白处隐藏键盘
	 */
	@Override
	public boolean onTouchEvent(MotionEvent event)
	{
		try
		{
			InputMethodManager imeMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
			imeMethodManager.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		return super.onTouchEvent(event);
	}
}
